﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CIT.WMS.houseWork.Helper;

namespace CIT.WMS.input
{
    public partial class CG_QD : Form
    {
        bool flag = false;
        bool result = false;
        string _PO_TypeCode = string.Empty;//单据类型：0采购单1委外单2客供单
        public CG_QD()
        {
            InitializeComponent();
            databind();
        }

        private void databind()
        {
            string strSql = string.Format(@"SELECT PO,POID FROM dbo.T_Bllb_POMain_tbpm WHERE Status='0' ORDER BY CreateTime DESC");
            DataTable dt_po = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
            DataRow dr = dt_po.NewRow();
            dr["PO"] = string.Empty;
            dr["POID"] = string.Empty;
            dt_po.Rows.InsertAt(dr, 0);
            cbo_PO.DisplayMember = "PO";
            cbo_PO.ValueMember = "POID";
            cbo_PO.DataSource = dt_po;
         
        }

        private void txt_reelid_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                ClearControl();
                string POID = string.Empty;
                //供应商代码|料号|唯一码|数量|生产日期（datacode或批次）|订单号|行号
                string[] strs = txt_reelid.Text.Trim().Split('|');
                if (strs.Length != 7)
                {
                    DataTable dt_po = Utils.NMS.QueryDataTable(Utils.uContext, "select Status,POID,PO_TypeCode from T_Bllb_POMain_tbpm where PO='" + txt_reelid.Text.Trim() + "'", new CIT.WMS.MESWcf.CmdParameter[0]);
                    if ( dt_po.Rows.Count== 0)//若是输入的不是采购单，那么就认为是来料条码
                    {
                        lbl_msg.Text = "物料条码有误或采购单不存在.";
                        lbl_msg.ForeColor = Color.Red;
                        txt_reelid.Text = string.Empty; ;
                        txt_reelid.Focus();
                        return;
                    }
                    else //判断采购单是否正确
                    {
                        if (SqlInput.ChangeNullToString(dt_po.Rows[0][0]) == "2")
                        {
                            lbl_msg.Text = "来料所属采购单已关闭.";
                            lbl_msg.ForeColor = Color.Red;
                        
                        }
                        else
                        {
                            cbo_PO.Text = txt_reelid.Text.Trim();
                            lbl_msg.Text = "采购单设置成功.";
                            lbl_msg.ForeColor = Color.Green;
                        }
                        _PO_TypeCode = SqlInput.ChangeNullToString(dt_po.Rows[0]["PO_TypeCode"]);//订单类型
                        txt_reelid.Text = string.Empty; ;
                        txt_reelid.Focus();
                        return;
                    }
                 
                }
                else
                {
                    if (cbo_PO.Text== string.Empty)
                    {
                        lbl_msg.Text = "请选择采购单";
                        lbl_msg.ForeColor = Color.Red;
                        txt_reelid.Text = string.Empty; ;
                        txt_reelid.Focus();
                        return;
                    }
                    #region 采购清点
                    //string[] strs = txt_reelid.Text.Trim().Split('|');
                    if (strs.Length == 7)
                    {
                        string po = strs[5].ToString();//采购订单号
                        if (po != cbo_PO.Text.Trim())
                        {
                            lbl_msg.Text = "物料不属于当前采购单";
                            lbl_msg.ForeColor = Color.Red;
                            txt_reelid.Text = string.Empty; ;
                            txt_reelid.Focus();
                            return;
                        }
                        string lot_no = strs[2].ToString();//批次号（唯一码）
                        string poid = string.Empty;//采购订单ID
                        string doc_no = string.Empty;//清点单号
                        string rownumber = string.Empty;//行号
                        string MaterialCode = strs[1].ToString(); //料号
                        string PO_DetailID=string.Empty;
                        int qty=0;
                        qty = SqlInput.ChangeNullToInt(strs[3].ToString(), 0);//数量
                        string strSql = string.Empty;
                        DataTable dt_po = Utils.NMS.QueryDataTable(Utils.uContext, "select Status,POID from T_Bllb_POMain_tbpm where PO='" + po + "'", new CIT.WMS.MESWcf.CmdParameter[0]);
                        if (SqlInput.ChangeNullToString(dt_po.Rows[0][0]) == "2")
                        {
                            lbl_msg.Text = "来料所属采购单已关闭.";
                            lbl_msg.ForeColor = Color.Red;
                            txt_reelid.Text = string.Empty; ;
                            txt_reelid.Focus();
                            return;
                        }
                        else
                        {
                            poid = SqlInput.ChangeNullToString(dt_po.Rows[0]["POID"]);
                        }    
                        rownumber = strs[6].ToString();//行号
                        strSql = string.Format(@"SELECT PO_DetailID,Quantity,ClearQty FROM dbo.T_Bllb_PODetail_tbpd WHERE PO='{0}'  AND RowNumber='{1}' and MaterialCode='{2}'", po, rownumber, MaterialCode);
                          DataTable dt_podetail = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                        if(dt_podetail.Rows.Count==0)
                        {
                             lbl_msg.Text = "采购单中不存在此物料.";
                            lbl_msg.ForeColor = Color.Red;
                            txt_reelid.Text = string.Empty; ;
                            txt_reelid.Focus();
                            return;
                        }
                        else
                        {
                            if (SqlInput.ChangeNullToInt(dt_podetail.Rows[0]["Quantity"],0) < SqlInput.ChangeNullToInt(dt_podetail.Rows[0]["ClearQty"],0) + qty)
                            {
                                lbl_msg.Text = "采购单中"+MaterialCode+"清点数量将会超过计划数";
                                lbl_msg.ForeColor = Color.Red;
                                txt_reelid.Text = string.Empty; ;
                                txt_reelid.Focus();
                                return;
                            }
                          PO_DetailID=dt_podetail.Rows[0][0].ToString();
                        }
                        strSql = string.Format(@"SELECT SerialNumber FROM T_Bllb_StorageDocDetail_tbsdd A LEFT JOIN 
dbo.T_Bllb_StorageDoc_tbsd B ON A.S_Doc_NO=B.S_Doc_NO WHERE  A.SerialNumber='{0}' AND B.S_Doc_Type='1'", txt_reelid.Text.Trim());
                        DataTable dt_serial= Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                        if (dt_serial.Rows.Count > 0)
                        {
                            lbl_msg.Text = "此物料已清点过";
                            lbl_msg.ForeColor = Color.Red;
                            txt_reelid.Text = string.Empty; ;
                            txt_reelid.Focus();
                            return;
                        }
                        //判断清点单是否已生成，若无则自动生成清点单
                        DataTable dt_doc = Utils.NMS.QueryDataTable(Utils.uContext, string.Format("SELECT  S_Doc_NO  FROM T_Bllb_StorageDoc_tbsd WHERE PO='{0}'and Create_Time>=CONVERT(CHAR(10),GETDATE(),120) AND S_Doc_Type='1'", cbo_PO.Text.Trim()), new CIT.WMS.MESWcf.CmdParameter[0]);
                        if (dt_doc.Rows.Count == 0)
                        {
                            dt_doc = Utils.NMS.QueryDataTable(Utils.uContext, string.Format("SELECT  RIGHT(S_Doc_NO,4)+1  FROM T_Bllb_StorageDoc_tbsd WHERE Create_Time>=CONVERT(CHAR(10),GETDATE(),120) AND S_Doc_Type='1'"), new CIT.WMS.MESWcf.CmdParameter[0]);
                            if (dt_doc.Rows.Count > 0)
                            {
                                doc_no = "QD" + DateTime.Now.ToString("yyMMdd") +SqlInput.ChangeNullToInt(dt_doc.Rows[0][0],0).ToString("0000");
                            }
                            else
                            {
                                doc_no = "QD" + DateTime.Now.ToString("yyMMdd") + "0001";
                            }
                           
                            strSql = string.Format(@"INSERT INTO dbo.T_Bllb_StorageDoc_tbsd
                                                    ( S_Doc_NO ,
                                                      S_Doc_Type ,
                                                      Create_Time ,
                                                      Creator ,
                                                      PO ,
                                                      POID
                                                    )
                                            VALUES  ( '{0}' , -- S_Doc_NO - nvarchar(50)
                                                      '1' , -- S_Doc_Type - nvarchar(10)
                                                      GETDATE() , -- Create_Time - datetime
                                                      '{1}' , -- Creator - nvarchar(50)
                                                      '{2}' , -- PO - nvarchar(50)
                                                      '{3}' -- POID - nvarchar(50)      
                                                    )", doc_no, Utils.uContext.UserIDk__BackingField , po, poid);  //供应商代码|料号|唯一码|数量|生产日期（datacode或批次）|订单号|行号
            
                            Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);

                       
                        }
                        else
                        {
                            doc_no = dt_doc.Rows[0][0].ToString();
                        }
                        int totalQty = 0;
                        strSql = string.Format(@"SELECT S_Doc_NO,QTY FROM T_Bllb_StorageDocMaterial_tsdm WHERE S_Doc_NO='{0}' AND RowNumber='{1}'", doc_no, rownumber);
                        //判断清点单中是否已存在某物料
                        DataTable dt_doc_material = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                    
                        if (dt_doc_material.Rows.Count == 0)
                        {  
                            strSql = string.Format(@"INSERT INTO dbo.T_Bllb_StorageDocMaterial_tsdm
                                                    ( S_Doc_NO ,
                                                      MaterialCode ,
                                                      QTY ,
                                                      RowNumber ,
                                                      PO_DetailID 
                                                    )
                                            VALUES  ( '{0}' , -- S_Doc_NO - nvarchar(50)
                                                      '{1}' , -- MaterialCode - nvarchar(50)
                                                      {2} , -- QTY - int
                                                      {3} , -- RowNumber - int
                                                      '{4}'  -- PO_DetailID - nvarchar(50) 
                                                    )", doc_no, MaterialCode, qty, rownumber, PO_DetailID);
                  
                            Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);
                            totalQty = qty;
                        }
                        else
                        {
                          
                            strSql = string.Format(@"UPDATE T_Bllb_StorageDocMaterial_tsdm SET QTY=QTY+{2} WHERE S_Doc_NO='{0}' AND RowNumber={1}",doc_no,rownumber,qty);
                      
                            Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);

                            totalQty = SqlInput.ChangeNullToInt(dt_doc_material.Rows[0]["QTY"].ToString(), 0) + qty;
                        }

                        strSql = string.Format(@"INSERT INTO dbo.T_Bllb_StorageDocDetail_tbsdd
                                                ( S_Doc_NO ,
                                                  MaterialCode ,
                                                  QTY ,
                                                  Create_Time ,
                                                  Creator ,
                                                  SerialNumber ,  
                                                  RowNumber ,
                                                  PO_DetailID,Lot_No
                                                )
                                        VALUES  ( '{0}' , -- S_Doc_NO - nvarchar(50)
                                                  '{1}' , -- MaterialCode - nvarchar(50)
                                                  {2} , -- QTY - int
                                                  GETDATE() , -- Create_Time - datetime
                                                  '{3}' , -- Creator - nvarchar(50)
                                                  '{4}' , -- SerialNumber - nvarchar(50)   
                                                  {5} , -- RowNumber - int
                                                  '{6}',  -- PO_DetailID - nvarchar(50)
                                                   '{7}'
                                                )", doc_no, MaterialCode, qty, Utils.uContext.UserIDk__BackingField, txt_reelid.Text.Trim(), rownumber, PO_DetailID, lot_no);
                         Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);
                         lbl_TotalQty.Text = totalQty.ToString();
                         lbl_QTY.Text = qty.ToString();
                         lbl_PO.Text = po.ToString();
                         lbl_MaterialCode.Text = MaterialCode;
                
                         //判断是否存在IQC单据若无，则新增
                         string iqc_no =string.Empty;//IQC检验单号                 


                         strSql = string.Format(@"SELECT [IQC_NO] FROM T_Bllb_IQCDoc_tbid WHERE S_DOC_NO='{0}' AND RowNumber={1} AND OVER_FLAG='N' AND CREATE_TIME>=CONVERT(CHAR(10),GETDATE(),120) AND Type='IQC'", doc_no, rownumber);
                         DataTable dt_IQC = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                         if (dt_IQC.Rows.Count > 0)//修改送检数量
                         {
                             iqc_no = dt_IQC.Rows[0][0].ToString();
                             strSql = string.Format(@"UPDATE T_Bllb_IQCDoc_tbid SET QTY=QTY+{1} WHERE IQC_NO='{0}'", iqc_no, qty);
                             Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);
                         }
                         else//新增IQC单据
                         {
                             DataTable dt_iqcwater = Utils.NMS.QueryDataTable(Utils.uContext, string.Format("SELECT TOP 1  RIGHT(IQC_NO,4)+1  FROM T_Bllb_IQCDoc_tbid WHERE Create_Time>=CONVERT(CHAR(10),GETDATE(),120) AND Type='IQC' ORDER BY IQC_NO DESC "), new CIT.WMS.MESWcf.CmdParameter[0]);
                             if (dt_iqcwater.Rows.Count > 0)
                             {
                                 iqc_no = "IQC" + DateTime.Now.ToString("yyMMdd") + SqlInput.ChangeNullToInt(dt_iqcwater.Rows[0][0], 0).ToString("0000");
                             }
                             else
                             {
                                 iqc_no = "IQC" + DateTime.Now.ToString("yyMMdd") + "0001";//IQC检验单号
                             }

                             strSql = string.Format(@"INSERT INTO dbo.T_Bllb_IQCDoc_tbid
                                                    ( IQC_NO ,
                                                      MaterialCode ,         
                                                      QTY ,     
                                                      CREATE_TIME ,   
		                                              S_DOC_NO,
		                                              RowNumber,PO
                                                    )
                                            VALUES  ( '{0}' , 
                                                      '{1}' ,  
                                                      {2} ,      
                                                      GETDATE() ,
		                                              '{3}',
		                                              '{4}' ,'{5}'
                                                    )",   iqc_no,MaterialCode,qty,doc_no,rownumber,po);
                             Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);
                         }
                        //保存物料SN到IQC单据中
                         strSql = string.Format(@"INSERT INTO T_Bllb_IQCProduct_tbip(
                                        TBIP_ID,
                                        IQC_NO,
                                        SERIAL_NUMBER,QTY)
                                        VALUES( 
                                        '{0}',
                                        '{1}',
                                        '{2}',{3})",
                                        Guid.NewGuid(),iqc_no,txt_reelid.Text.Trim(),qty
                                         );
                        Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);

                        //采购单物料清点数累计
                        strSql = string.Format(@" UPDATE T_Bllb_PODetail_tbpd SET ClearQty= ISNULL(ClearQty,0)+{3}  WHERE PO='{0}' AND RowNumber='{1}' and MaterialCode='{2}'", po, rownumber, MaterialCode,qty);
                        Utils.NMS.Exectransql(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0], out flag, out result);

                    }
                    #endregion
                    else
                    {
                        lbl_msg.Text = "物料条码不符合，无法解析";
                        lbl_msg.ForeColor = Color.Red;
                        txt_reelid.Text = string.Empty; ;
                        txt_reelid.Focus();
                        return;
                    }
                    lbl_msg.Text = "OK";
                    lbl_msg.ForeColor = Color.Green;
                    txt_reelid.Text = string.Empty; ;
                    txt_reelid.Focus();
                }
             
            }
        }

        private void cbo_PO_SelectedIndexChanged(object sender, EventArgs e)
        {
            ClearControl();
        }

        private void ClearControl()
        {
            lbl_MaterialCode.Text = string.Empty;
            lbl_PO.Text = string.Empty;
            lbl_QTY.Text = string.Empty;
            lbl_TotalQty.Text = string.Empty;
            lbl_msg.Text = string.Empty;
        }

        private void cbo_PO_LostFocus(object sender, EventArgs e)
        {
            if (cbo_PO.Text.Trim() != string.Empty)
            {
                string strSql = string.Format(@"SELECT Status,PO_TypeCode FROM T_Bllb_POMain_tbpm WHERE PO = '{0}'", cbo_PO.Text.Trim());
                DataTable dt_po = Utils.NMS.QueryDataTable(Utils.uContext, strSql, new CIT.WMS.MESWcf.CmdParameter[0]);
                if (dt_po.Rows.Count == 0)
                {
                    lbl_msg.Text = "订单不存在";
                    lbl_msg.ForeColor = Color.Red;
                    return;
                }
                else if (SqlInput.ChangeNullToString(dt_po.Rows[0][0]) == "2")
                {
                    lbl_msg.Text = "订单已关闭";
                    lbl_msg.ForeColor = Color.Red;
                    return;
                }
                _PO_TypeCode = SqlInput.ChangeNullToString(dt_po.Rows[0]["PO_TypeCode"]);//订单类型
                lbl_msg.Text = "订单设置OK";
                lbl_msg.ForeColor = Color.Green;
                return;
            
            }
        }
    }
}